package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDTO;
import com.heima.model.search.dto.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Resource
    MongoTemplate mongoTemplate;
    @Resource
    BehaviorFeign behaviorFeign;

    @Async("taskExecutor")  //此方法会调用taskExecutor
    @Override
    public void insert(UserSearchDTO userSearchDto) {
        //1 参数检查
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        //2 查询行为实体
        ResponseResult<ApBehaviorEntry> behaviorResponse = behaviorFeign
                .findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId());
        if (!behaviorResponse.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResponse.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        log.info("ApUserSearchServiceImpl insert entryId:{}, searchWords:{}", entryId, searchWords);
        //3 查询当前用户搜索的关键词是否存在
        Query query = Query.query(Criteria.where("keyword").is(searchWords).and("entryId").is(entryId));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        //存在则更新时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        } else {
            apUserSearch = new ApUserSearch();
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setEntryId(apBehaviorEntry.getId());
            apUserSearch.setKeyword(searchWords);
            mongoTemplate.save(apUserSearch);
        }
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO historySearchDto) {
        if(historySearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntry = behaviorFeign.
                findByUserIdOrEquipmentId(user == null ? null : user.getId(), historySearchDto.getEquipmentId());
        ApBehaviorEntry data = behaviorEntry.getData();
        if(data == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId()).and("entryId").is(data.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }

    /**
     * 查询用户搜索记录，显示10条
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        if (userSearchDto.getMinBehotTime() == null) {
            userSearchDto.setMinBehotTime(new Date());
        }
        List<ApUserSearch> userSearchList = new ArrayList<>();
        int size = 10;
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.
                findByUserIdOrEquipmentId(user == null ? null : user.getId(), userSearchDto.getEquipmentId());
        if (behaviorResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, behaviorResult.getErrorMessage());
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResult.getData();
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (apBehaviorEntry != null) {
            //查询当前用户的搜索列表 按时间倒叙 limit
            Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("createdTime").
                    lt(userSearchDto.getMinBehotTime())).with(Sort.by(Sort.Direction.DESC,"createdTime")).limit(size);
            userSearchList = mongoTemplate.find(query, ApUserSearch.class);
            return ResponseResult.okResult(userSearchList);
        }
        return ResponseResult.okResult(userSearchList);
    }
}
